const express = require('express');
const router = express.Router();
const { Membership } = require('../../models');
const { Op } = require('sequelize');
const { NotFound } = require('http-errors');
const { success, failure } = require('../../utils/responses');
const { setKey, getKey, getKeysByPattern, delKey } = require('../../utils/redis');
/**
 * 白名单参数过滤
 * */
const filterBody = (data) => {
  return {
    name: data.name,
    durationMonths: data.durationMonths,
    price: data.price,
    rank: data.rank,
    description: data.description,
  };
};

/**
 * 公共方法: 查询当前章节
 * */

async function getMembership(req) {
  const { id } = req.params;
  const redisKey = `membership:${id}`;
  let redisData = await getKey(redisKey);
  if (!redisData) {
    redisData = await Membership.findByPk(id);
    if (!redisData) {
      throw new NotFound(`ID: ${id}的章节为找到`);
    }
    await setKey(redisKey, redisData);
  }
  return redisData;
}

/**
 * 查询定价列表
 * */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    // 当前第几页，如果不传默认第一页
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    // 当前多少条数据，如果不传默认10条数据
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    // 计算offset
    const offset = (currentPage - 1) * pageSize;
    const redisKey = `memberships:${currentPage}/${pageSize}`;
    const redisData = await getKey(redisKey);
    if (redisData) {
      return success(res, 'redis数据查询成功', redisData);
    }
    const condition = {
      where: {},
      order: [
        ['ranK', 'ASC'],
        ['id', 'DESC'],
      ],
      limit: pageSize,
      offset,
    };

    if (query.name) {
      condition.where.name = {
        [Op.like]: `%${query.name}%`,
      };
    }

    const { count: total, rows } = await Membership.findAndCountAll(condition);
    const _data = {
      memberships: rows,
      pagination: {
        total,
        currentPage,
        pageSize,
      },
    };
    await setKey(redisKey, _data);
    success(res, '查询成功', _data);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询会员详情
 * */
router.get('/:id', async function (req, res) {
  try {
    const memberships = await getMembership(req);
    success(res, '查询成功', { memberships });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建会员
 * */
router.post('/', async function (req, res) {
  try {
    const body = filterBody(req.body);
    // 创建章节并对课程章节数量+1
    const memberships = await Membership.create(body);
    await clearCache();
    success(res, '创建成功', { memberships }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除会员信息
 * */
router.delete('/:id', async function (req, res) {
  try {
    const membership = await getMembership(req);
    // 删除章节并对课程章节-1
    await membership.destroy();
    await clearCache(req.params.id);
    success(res, '删除成功');
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新会员信息
 * */
router.put('/:id', async function (req, res) {
  try {
    const membership = await getMembership(req);
    const body = filterBody(req.body);
    const data = await membership.update(body);
    await clearCache(req.params.id);
    success(res, '更新成功', data);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 清除缓存
 * @returns {Promise<void>}
 *
 */
async function clearCache(id = null) {
  const keys = await getKeysByPattern('memberships:*');
  if (keys.length !== 0) {
    await delKey(keys);
  }
  if (id) {
    const keys = Array.isArray(id) ? id.map((item) => `membership:${item}`) : `membership:${id}`;
    await delKey(keys);
  }
}
module.exports = router;
